﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace NetCore
{
    public class ConfigHelper
    {

        public const string Cache_Entity_Key = "Cache_Entity_Key_";

        /// <summary>
        /// 密码验证码标识
        /// </summary>
        public const string RESET_PASSWORD_SEND_VER_CODE = "RESET_PASSWORD_SEND_VER_CODE";

        /// <summary>
        /// 邮箱激活码标识
        /// </summary>
        public const string EMAIL_SEND_ACTIVE_VER_CODE = "EMAIL_SEND_ACTIVE_VER_CODE";

        /// <summary>
        /// 获取底层缓存实例
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static string GetCacheModelKey(Type type,string id)
        {
            return (Cache_Entity_Key + type.Name + "_" + id).ToUpper();
        }
        /// <summary>
        /// 获取配置文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static T GetAppSettings<T>(string key, string fileName= "appsettings") where T : class, new()
        {
            var baseDir = AppContext.BaseDirectory;
            //var indexSrc = baseDir.IndexOf("src");
            //var subToSrc = baseDir.Substring(0, indexSrc);
           // var currentClassDir = subToSrc + "src" + Path.DirectorySeparatorChar + "StutdyEFCore.Data";
            IConfiguration config = new ConfigurationBuilder()
                .SetBasePath(baseDir)
                .Add(new JsonConfigurationSource { Path = fileName+".json", Optional = false, ReloadOnChange = true })
                .Build();
            var appconfig = new ServiceCollection()
                .AddOptions()
                .Configure<T>(config.GetSection(key))
                .BuildServiceProvider()
                .GetService<IOptions<T>>()
                .Value;
         
            return appconfig;
        }
    }
}
